import Vue from "vue";
import axios from "axios";
import { getToken } from "../utils/storage";
import { baseUrl } from "../utils/config";

axios.defaults.baseURL = baseUrl;
axios.defaults.timeout = 5000;
// const baseHeader = {
//   token: getToken(),
// };
// 请求拦截
axios.interceptors.request.use((config) => {
  config.headers = {
    ...config.headers,
    token: getToken(),
  };
  return config;
});

// 响应拦截
axios.interceptors.response.use(
  (response) => {
    // console.log("response", response);
    return response;
  },
  (error) => {
    console.log("error", error);
    return error;
  }
);

// 链接到原型
Vue.prototype.$axios = axios;
Vue.prototype.$req = {
  get: ({ url, data = {}, headers = {} }) => {
    return axios({
      method: "GET",
      url,
      params: data,
      headers: {
        ...headers,
      },
    }).then((res) => {
      return res;
    });
  },
  post: ({ url, data = {}, headers = {} }) => {
    return axios({
      method: "POST",
      url,
      data,
      headers: {
        ...headers,
      },
    }).then((res) => {
      return res;
    });
  },
};

export default axios;
